package com.luohoufa.ms.order.controller;

import com.luohoufa.ms.order.convert.OrderFormToOrderDTOCovert;
import com.luohoufa.ms.order.dto.OrderDTO;
import com.luohoufa.ms.order.enums.ResultEnum;
import com.luohoufa.ms.order.exception.OrderException;
import com.luohoufa.ms.order.form.OrderForm;
import com.luohoufa.ms.order.service.OrderService;
import com.luohoufa.ms.order.utils.ResultVOUtil;
import com.luohoufa.ms.order.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        /**
         * 1. 参数检验
         * 2. 查询商品信息（调用商品服务）
         * 3. 计算总价
         * 4. 扣库存（调用商品服务）
         * 5. 订单入库
         */
        // 1. 参数检验
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确，orderForm={}", orderForm);
            throw new OrderException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }

        // orderForm -> orderDTO
        OrderDTO orderDTO = OrderFormToOrderDTOCovert.convert(orderForm);

        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【创建订单】购物车信息为空");
            throw new OrderException(ResultEnum.CART_EMPTY);
        }

        OrderDTO result = orderService.create(orderDTO);

        Map<String, Object> map = new HashMap<>();
        map.put("orderId", result.getOrderId());

        return ResultVOUtil.success(map);

    }


    @PostMapping("/finish")
    public ResultVO<OrderDTO> finish(@RequestParam("orderId") String orderId) {
        OrderDTO orderDTO = orderService.finish(orderId);
        return ResultVOUtil.success(orderDTO);
    }

}
